package controllers

import (
	"apiTest/models"
	"encoding/json"
	"github.com/beego/beego/v2/core/logs"
	beego "github.com/beego/beego/v2/server/web"
	"github.com/beego/i18n"
	"strconv"
)
type NestPreparer interface {
	NestPrepare()
}

type TestController struct {
	beego.Controller
	i18n.Locale
}

func (o *TestController) Prepare() {
	o.EnableXSRF = false
	logs.Info("base controller prepare func run")
	if app, ok := o.AppController.(NestPreparer); ok {
		app.NestPrepare()
	}
}

// @Title Get
// @Description find test by uid
// @Param	uid		path 	string	true		"the uid you want to get"
// @Success 200 {object} models.UserTable
// @Failure 403 :uid is empty
// @router /:uid [get]
func (o *TestController) Get() {
	var user models.UserTable
	uid, err := strconv.Atoi(o.Ctx.Input.Param(":uid"))
	if err == nil {
		o.Data["json"] = err.Error()
	} else {
		user.ID = uid
		err := models.DefaultOrm.Read(&user)
		if err != nil {
			o.Data["json"] = err.Error()
		} else {
			o.Data["json"] = user
		}
	}
	o.ServeJSON()
}

// @Title Create
// @Description create tese
// @Param	body		body 	models.UserTable	true		"The Test content"
// @Success 200 {string} models.UserTable.Id
// @Failure 403 body is empty
// @router / [post]
func (o *TestController) Post() {
	var user models.UserTable
	json.Unmarshal(o.Ctx.Input.RequestBody, &user)
	uid, err := models.DefaultOrm.Insert(&user)
	if err != nil {
		o.Data["json"] = err.Error()
	} else {
		o.Data["json"] = map[string]string{"ObjectId": strconv.Itoa(int(uid))}
	}
	o.ServeJSON()
}

// @Title Update
// @Description update the user
// @Param	uid		path 	string	true		"The uid you want to update"
// @Param	body		body 	models.UserTable	true		"body for user content"
// @Success 200 {object} models.UserTable
// @Failure 403 :uid is not int
// @router /:uid [put]
func (o *TestController) Put() {
	var user models.UserTable
	uid, err := strconv.Atoi(o.Ctx.Input.Param(":uid"))
	if err != nil {
		o.Data["json"] = err.Error()
	} else {
		user.ID = uid
		err := models.DefaultOrm.Read(&user)
		if err != nil {
			o.Data["json"] = err.Error()
		} else {
			json.Unmarshal(o.Ctx.Input.RequestBody, &user)
			_, err := models.DefaultOrm.Update(&user)
			if err != nil {
				o.Data["json"] = err.Error()
			} else {
				o.Data["json"] = user
			}
		}
	}
	o.ServeJSON()
}

// @Title Delete
// @Description delete the user
// @Param	uid		path 	string	true		"The uid you want to delete"
// @Success 200 {string} delete success!
// @Failure 403 uid is empty
// @router /:uid [delete]
func (o *TestController) Delete() {
	uid, err := strconv.Atoi(o.GetString(":uid"))
	if err != nil {
		o.Data["json"] = err.Error()
	} else {
		_, err := models.DefaultOrm.Delete(&models.UserTable{ID: uid})
		if err == nil {
			o.Data["json"] = "delete success!"
		}
	}
	o.ServeJSON()
}